package eu.connect.jmswrapper;

import javax.jms.*;

import org.apache.activemq.ActiveMQConnectionFactory;

public class ConnectJMSCalleeProxy implements MessageListener {
	
	private Class<?> interfaceClass;
	private String interfaceLastName;
	private Object target;
	private TopicConnection tConnection;
	private TopicSession tSession;
	private TopicSubscriber subscriber;
	private Topic topic;
	
	
	public ConnectJMSCalleeProxy(String interfaceName, Object target) {
		String s[]=interfaceName.split("\\.");
		this.interfaceLastName = s[s.length - 1];
		
		try {
			this.interfaceClass = Class.forName(interfaceName);
			this.target = target;
			
			ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://" + TargetHost.getHost() + ":61616");
			this.tConnection = connectionFactory.createTopicConnection();
			this.tSession = tConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
			this.topic = tSession.createTopic("connect."+this.interfaceLastName);
		}
		catch (ClassNotFoundException e1){}
//		catch (NamingException e2) {}
		catch (JMSException e3){}
	}
	
	public void start() {
		try {
			subscriber = tSession.createSubscriber(this.topic, null, true);
			subscriber.setMessageListener(this);
			tConnection.start();
		}
		catch (JMSException e) {}
	}
	
	public void exit() {
		try {
			tConnection.close();
		} catch (JMSException e) {}
	}

	@Override
	public void onMessage(Message message) {
		try {
			ConnectJMSReceiver receiver = new ConnectJMSReceiver(tSession,topic,interfaceClass,target,message);
			receiver.start();
		} catch (JMSException e) {
			e.printStackTrace();
		}

	}

}
